package com.centerserver;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ServerSocket;
import java.net.Socket;

class SendSpsPps extends Thread {
	
	private DatabaseManager mDatabaseManager;
	private String mIpAddress;
	private ServerSocket mServerSocket;
	public SendSpsPps(DatabaseManager databaseManager, String ipAddress) {
		mDatabaseManager = databaseManager;
		mIpAddress = ipAddress;
		
		try {
			mServerSocket = new ServerSocket(CenterServerConfig.SENDTO_MONITOR_END_TCP_PORT);
		} catch (IOException e) {
			System.out.println("IOException in SendSpsPps");
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		
		Socket socket = null;
		OutputStream outputStream = null;
		try {
			socket  = mServerSocket.accept();
		} catch (IOException e) {
			System.out.println("IOException in SendSpsPps");
			e.printStackTrace();
		}
		
		byte[] sps = null;
		byte[] pps = null;
		try {
			sps = mDatabaseManager.getSpsByCaptureEndName(mIpAddress).getBytes("ISO-8859-1");
			pps = mDatabaseManager.getPpsByCaptureEndName(mIpAddress).getBytes("ISO-8859-1");
		} catch (UnsupportedEncodingException e1) {
			System.out.println("UnsupportedEncodingException in SendSpsPps");
			e1.printStackTrace();
		}
		try {
			outputStream = socket.getOutputStream();
		} catch (IOException e) {
			System.out.println("IOException in SendSpsPps");
			e.printStackTrace();
		}
		
		// send SPS & PPS to monitor end
		try {
			outputStream.write(sps.length);
			outputStream.write(sps);
			outputStream.write(pps.length);
			outputStream.write(pps);
		} catch (IOException e) {
			System.out.println("IOException in SendSpsPps");
			e.printStackTrace();
		}
	}
}
